<template>
  <div class="content">
    <div class="cloud-header">
      <h2 class="r-title-h2">新增产品</h2>
    </div>
    <div class="cloud-body">
      <div class="r-rchart-title">请填写商品信息</div>
      <Form :label-width="130" :model="data" :rules="validationRules" ref="form" :top="0.2" showErrorTip>
        <FormItem label="商品名称：" prop="name">
          <input type="text" v-model="data.name" v-width="200" placeholder="请输入商品名称" />
        </FormItem>
        <FormItem label="列表图片：" prop="image_list">
          <Upload v-model="data.image_list" :limit="6"></Upload>
        </FormItem>
        <FormItem label="商品上架：" prop="putaway">
          <h-switch v-model="data.putaway" :trueValue="1" :falseValue="0"></h-switch>
        </FormItem>
        <FormItem label="产品单价：" prop="price">
          <div class="h-input-group" v-width="200">
            <span class="h-input-addon">¥</span>
            <NumberInput :precision="2" type="text" v-model="data.price" />
          </div>
        </FormItem>
        <FormItem label="折扣：" prop="price_discount">
            <div class="h-input-group" v-width="200">
              <NumberInput :precision="1" type="text" :min="0" :max="10" v-model="data.price_discount" />
               <span class="h-input-addon">折</span>
            </div>
        </FormItem>
        <FormItem label="折后价格：" prop="discount_price">
          <div style="display:flex;align-items: center; justify-content: flex-start; color: #555555">
            <div class="h-input-group margin-right" v-width="200">
              <span class="h-input-addon">¥</span>
              <NumberInput disabled :precision="2" type="text" v-model="discount_price" />
            </div>
            抹去零头：<h-switch v-model="maling" :trueValue="1" :falseValue="0" @change="intMaling"></h-switch>
          </div>
        </FormItem>
        </FormItem>
        <FormItem label="产品分类：" prop="classify_id">
          <div class="r-item-class">
            <Select v-model="data.classify_id" :datas="dataOption" keyName="_id" titleName="name" v-width="200" class="r-class-select"></Select>
          </div>
        </FormItem>
        <FormItem label="商品标签：" prop="status">
          <Select v-model="data.status" :datas="statusOption" keyName="key" titleName="label" v-width="200"></Select>
          <!-- <DatePicker v-model="data.date" :format="format" v-width="180"></DatePicker> -->
        </FormItem>
        <FormItem label="商品规格：" prop="goods_spec">
          <a v-if="!is_spce" href="javascript:void(0);" @click="addSpecItem">添加规格</a>
          <div v-if="is_spce" >
            <table class="r-goods-spce" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <th>规格名</th>
                <th>价格</th>
                <th>折扣</th>
                <th>折扣后价格</th>
              </tr>
              <tr v-for="item,index in data.goods_spec" :key="index">
                <td class="r-spce-display">
                  <i class="iconfont icon-Delete" @click="intDel(index)"></i>
                  <input type="text" v-model="item.spce_name" placeholder="规格名称" />
                </td>
                <td>
                  <div class="h-input-group" >
                    <span class="h-input-addon">¥</span>
                    <NumberInput :precision="2" type="text" v-model="item.price" placeholder="规格价格" />
                  </div>
                </td>
                <td>
                  <div class="h-input-group" >
                    <NumberInput :precision="1" type="text" :min="0" :max="10" v-model="item.price_discount" placeholder="优惠折扣" />
                    <span class="h-input-addon">折</span>
                  </div>
                </td>
                <td>
                  <div class="h-input-group" >
                    <span class="h-input-addon">¥</span>
                    <NumberInput :precision="2" type="text" disabled v-model="item.discount_price" placeholder="折扣后价格" />
                  </div>
                </td>
              </tr>
            </table>
            <div class="r-goodspce-add" @click="addSpecItem"> <i class="h-icon-plus"></i> </div>
          </div>
        </FormItem>
        <FormItem label="排序号：" prop="sort" class="r-rchart-item">
          <NumberInput type="text" v-model="data.sort" v-width="200" /><span class="r-item-tips">请填写数字，数字越大越靠前</span>
        </FormItem>
        <FormItem label="选择门店" prop="shop_list">
            <Select v-model="data.shop_list" :datas="shopList" :multiple="true" keyName="_id" titleName="branch_name"  v-width="400"></Select>
        </FormItem>
        <FormItem label="产品说明：" class="r-rchart-item">
          <!-- <textarea v-model="data.abstract" v-width="260" rows="3"></textarea> -->
          <div ref="editorElem" style="text-align:left;"></div>
        </FormItem>
      </Form>
      <div class="r-submit-button">
        <Button color="primary"  @click="intSubmit"><i class="iconfont icon-save r-submit-icon"></i>保存</Button>
        <Button v-if="!id" @click="reset"><!-- <i class="iconfont icon-cancel r-submit-icon"></i> -->重置</Button>
        <Button v-else @click="cancal"><i class="iconfont icon-cancel r-submit-icon"></i>取消</Button>
      </div>
    </div>

  </div>
</template>
<script type="text/javascript">
import Upload from '@/components/upload/index'
import E from '@/utils/wangEditor.js'
export default {
  name: '',
  components:{
    Upload
  },
  data() {
    return {
      // 抹零开关
      maling:false,

      id:'',
      discount_price:'',
      _uniqueid:'',
      shopList:[],
      is_spce:false,
      data: {
        name: '',
        image_list: [],
        price: '',
        putaway: 1,
        status: '',
        sort: '',
        price_discount:'',
        discount_price:'',
        abstract:'',
        classify_id:'',
        creation_time:'',
        deleted:1,
        goods_spec:[],
        shop_list:[]
      },
      validationRules: {
        rules:{
        },
        required: ['name','image_list','price','classify_id','status','price_discount','sort','shop_list']
      },
      format: 'YYYY-MM-DD',
      dataOption:[],

      statusOption: [{
        key: 1,
        label: '正常'
      }, {
        key: 2,
        label: '招牌'
      }, {
        key: 3,
        label: '推荐'
      }, {
        key: 4,
        label: '新品'
      }],

      /**
       * 富文本
       * @type {[type]}
       */
      editor:null,
    }
  },
  watch:{
    data:{
        handler(val,old){
          this.toCalc();
        },
        deep:true
    },

  },
  mounted(){
    this._uniqueid = this.$cloud.userInfo()._uniqueid
    // 创建富文本
    this.editor = new E(this.$refs.editorElem);

    // 富文本配置
    this.editor.customConfig.uploadImgShowBase64 = false;   // 使用 base64 保存图片
    // 将图片大小限制为 200kb
    this.editor.customConfig.uploadImgMaxSize = 0.2 * 1024 * 1024;
    // 限制一次最多上传 1 张图片
    this.editor.customConfig.uploadImgMaxLength = 1;

    // editor.customConfig.uploadImgServer = '/upload'  // 上传图片到服务器
    //自定义图片上传整个过程
    let _this = this;
    this.editor.customConfig.customUploadImg = async function (files, insert) {
        let imgUrl = '';
        let img = await _this.$cloud.upload(files[0]);
        if(img){
            imgUrl = img;
        }else{
          _this.$Message.error('网络异常，请稍后重试！')
        }
        insert(imgUrl)
    }

    this.editor.create();


    // 获取商品分类
    this.getClass();
    this.getShopList()

    // console.log('query',this.$route.query);
    if(this.$route.query.id){
      this.id = this.$route.query.id;
      /**
       * 获取更新数据
       */
      this.getEditData();
    }
  },
  methods: {
    /**
     * 抹零控制器
     * @return {[type]} [description]
     */
    intMaling(){
      this.toCalc();
    },

    /**
     * 动态计算折后价格
     */
    toCalc(){
        let num = 2;
        // 判断是否抹去价格零头
        if(this.maling){
          num = 0
        }else{
          num = 2;
        }
        this.discount_price = (this.data.price * this.data.price_discount * 10 / 100).toFixed(num);
        this.data.goods_spec.forEach(item =>{
          item['discount_price'] = (item.price * item.price_discount * 10 / 100).toFixed(num);
        })
    },


    /**
     * 获取商品分类列表
     * @return {[type]} [description]
     */
    async getClass(){
      let ret = await this.$cloud.name('goods_classify').select();
      if(ret){
        this.dataOption = ret;
        // this.loading = false;
      }else{
        this.$Message.error('网络异常，请稍后重试！')
      }
    },

    /**
     * 获取更新数据
     * @return {[type]} [description]
     */
    async getEditData(){
      let ret = await this.$cloud.name('goods').where({_id:this.id}).select();
      if(ret){
        this.data = ret[0];
        this.editor.txt.html(this.data.abstract);
        if(this.data.goods_spec.length > 0){
          this.is_spce = true;
        }
      }else{
        this.$Message.error('网络异常，请稍后重试！')
      }
    },

    /**
     * 上传产品
     * @return {[type]} [description]
     */
    async intSubmit(){
      // console.log("富文本内容")
      //商品详情
      if(!this.editor.txt.text()){
        this.$Message.error('请输入商品说明！')
        return false
      }
      this.data.abstract = this.editor.txt.html();

      this.data.discount_price = this.discount_price;
      let validResult = this.$refs.form.valid();
      if(validResult.result){
        if(!this.id){
        // 发布新商品
          let ret = await this.$cloud.name('goods').insert(this.data);
          if(ret){
            // 清空表单
            this.reset();
            this.$Message.success('新增产品成功！')
          }else{
            this.$Message.error('网络异常，请稍后重试！')
          }
        }else{
          // 更新商品
          let ret = await this.$cloud.name('goods').where({_id:this.id}).update(this.data);
          if(ret){
            // 更新成功之后返回列表
            this.$Message.success('更新产品成功！')
            history.back();
          }else{
            this.$Message.error('网络异常，请稍后重试！')
          }
        }
      }
    },
    getShopList() {
      this.$cloud.name('shop').where({ _uniqueid: this._uniqueid }).limit(-1).select().then(res => {
        console.log('店铺列表', res);
        this.shopList = res;
      }).catch(error => {
        console.log('数据库操作报错', error);
        this.$Notice.error(error.data.msg);
      });
    },

    /**
     * 重置表单
     * @return {[type]} [description]
     */
    reset(){
      //清空表单
      this.is_spce = false;
      this.data = {
        name: '',
        image_list: [],
        price: '',
        putaway: 1,
        status: '',
        sort: '',
        price_discount:'',
        abstract:'',
        classify_id:'',
        creation_time:'',
        deleted:1,
        goods_spec:[],
      }
    },
    /**
     * 取消
     * @return {[type]} [description]
     */
    cancal(){
      history.back();
    },

    /**
     * 添加规格项
     */
    addSpecItem(){
      this.is_spce = true;
      let spce = {
        spce_name:'',
        price:'',
        price_discount:'',
        discount_price:'',
      }

      this.data.goods_spec.push(spce);
    },

    /**
     * 删除规格项
     * @param  {[type]} index [description]
     * @return {[type]}       [description]
     */
    intDel(index){
      this.data.goods_spec.splice(index,1);
      if(this.data.goods_spec.length == 0){
        this.is_spce = false;
      }
    }
  }
}

</script>
<style type="text/css" lang="less">
.margin-right{
  margin-right: 20px;
}
.r-submit-button {
  text-align: center;
  margin-top: 120px;

  button {
    margin: 0px 10px;
  }

  .r-submit-icon {
    margin-right: 5px;
  }
}

.r-rchart-title {
  color: #999;
  border-bottom: solid 1px #E4E4E4;
  padding-bottom: 10px;
  margin-bottom: 40px;
}

.r-rchart-upload {
  background-color: rgba(242, 242, 242, 1);
  border:solid 1px #ededed;
  width: 80px;
  height: 80px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: #666;
  margin-bottom: 0px;
  cursor: pointer;
  i {
    font-size: 32px !important;
    color: #dfdfdf;
  }
}
.r-rchart-imglist{
  width: 80px;
  height: 80px;
  display:flex;
  justify-content: center;
  align-items: center;
  border-radius:5px;
  background-color: rgba(242, 242, 242, 1);
  border:solid 1px #ededed;
  position: relative;
  overflow: hidden;
  position: relative;
  img{
    width: auto; 
    height: auto;
    max-width: 100%;
    max-height: 100%;
  }
  .r-rchart-delete{
    display:none;
  }
  &:hover .r-rchart-delete{
    display:flex;
    justify-content: center; 
    align-items: center;
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.4);
    cursor: pointer;
    color: #fff;
    i{
      font-size: 30px;
    }
  }
}
.r-upload-list{
  display:flex;
  justify-content: flex-start; 
  align-items: center;
  >div{
    margin-right: 10px;
  }
}

.r-item-tips {
  color: #999999;
}

.h-form-item {
  margin: 10px 0;
}

.r-goods-spce{
  border:solid 1px #efefef;
  th{
    width: 160px;
    height: 40px;
    text-align: center;
    border-left: 1px solid #efefef;
    border-bottom: 1px solid #efefef;
    &:first-child{
      border-left:0px;
    }
/*    border: solid 1px #efefef;*/
  }
  td{
    width: 160px;
    text-align: center;
    padding: 10px 20px;
  }
  .r-spce-display{
    display:flex;
    justify-content: center;
    align-items: center;
    padding-left: 10px;
    i{
      margin-right: 10px;
      cursor: pointer;
      &:hover{
        color: #999;
      }
    }
  }
}
.r-goodspce-add{
  border: 1px dashed #ccc;
  border-top: 0px;
  line-height: 30px;
  width: 120px;
  height: 30px;
  text-align: center;
  border-radius: 5px;
  border-top-left-radius: 0px;
  border-top-right-radius: 0px;
  margin-left:290px;
  cursor: pointer;
}

.r-rchart-item .h-form-item-wrap {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  .h-numberinput {
    margin-right: 10px;
  }

  .r-item-tips {
    color: #999999;
  }

}
.h-form .h-form-item-wrap{
  line-height: 32px !important;
}
.r-item-class{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .r-class-select{
    margin-right: 10px;
  }
  .r-class-add{
      cursor: pointer;
  }
}
</style>
